package com.qd.pay.repository;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdqidi.db.BaseService;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.FileUtil;
import com.qd.pay.config.PayInfoConfig;
import com.qd.pay.mapper.OrderBodyMapper;
import com.qd.pay.model.OrderBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

/**
 * @author sjk
 */
@Repository
@Slf4j
public class OrderBodyRepository extends BaseService<OrderBodyMapper, OrderBody> {

    @Resource
    private PayInfoConfig payInfo;
    private static final String CERTIFICATE_FILE_SUFFIX = ".p12";

    public boolean isExists(String id) {
        return getBaseMapper().exists(new QueryWrapper<OrderBody>().eq("id", id));
    }

    public File getCertificate(String appId) {
        try {
            if (!StringUtils.hasLength(payInfo.getWxFilePath())) {
                throw new ApiException(3, "请配置文件存储地址");
            }
            File file = new File(payInfo.getWxFilePath());
            if (!file.exists()) {
                boolean b = file.mkdirs();
                if (!b) {
                    log.info("文件夹创建失败: {}", file.getPath());
                    throw new ApiException(3, "文件夹创建失败");
                }
            }
            file = new File(payInfo.getWxFilePath() + appId + CERTIFICATE_FILE_SUFFIX);
            if (!file.exists()) {
                ByteArrayInputStream stream = baseMapper.getCertificate(appId);
                if (null == stream) {
                    throw new ApiException(3, "请配置证书");
                } else {
                    try {
                        byte[] bytes = FileUtil.inputStreamToByte(stream);
                        bytes = getByte(bytes);
                        FileUtil.createFile(bytes, payInfo.getWxFilePath(), appId + CERTIFICATE_FILE_SUFFIX);
                        file = new File(payInfo.getWxFilePath() + appId + CERTIFICATE_FILE_SUFFIX);
                    } finally {
                        stream.close();
                    }
                }
            }
            return file;
        } catch (IOException e) {
            throw new ApiException(e);
        }
    }

    public byte[] getByte(byte[] value) throws IOException {
        byte[] c = null;
        if (null != value) {
            try (ByteArrayInputStream bin = new ByteArrayInputStream(value)) {
                try (java.io.DataInputStream in = new java.io.DataInputStream(bin)) {
                    in.readUTF();
                    in.readUTF();
                    in.readInt();
                    c = new byte[in.available()];
                    in.read(c, 0, c.length);
                }
            }
        }
        return c;
    }
}